package com.yuanhua.xcxmng.wechat.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.google.common.collect.Lists;
import com.yuanhua.xcxmng.wechat.cache.LocalCache;
import com.yuanhua.xcxmng.wechat.cons.TestTypeEnum;
import com.yuanhua.xcxmng.wechat.entity.UdVO;
import com.yuanhua.xcxmng.wechat.entity.UserData;
import com.yuanhua.xcxmng.wechat.entity.UserDataQuery;
import com.yuanhua.xcxmng.wechat.service.MyService;
import com.yuanhua.xcxmng.wechat.service.UserDataService;
import com.yuanhua.xcxmng.wechat.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/wechat/test")
public class TestResultControoler extends BaseController {

    @Autowired
    private WxMaService     wxService;

    @Autowired
    private MyService       myService;

    @Autowired
    private UserDataService userDataService;

    @GetMapping("save")
    public String save(String threeSession, String type, String value, int cqch) {
        // 用户信息校验
        if (StringUtils.isBlank(threeSession)) {
            return "empty threeSession";
        }
        String sessionCode = LocalCache.getInStance().getLocalCache(threeSession);
        if (StringUtils.isBlank(sessionCode)) {
            return "fail";
        }
        String sessionKey = StringUtils.split(sessionCode, "^#^")[0];
        String openId = StringUtils.split(sessionCode, "^#^")[1];
        int cltype = TestTypeEnum.getEnumByType(type).getCode();
        try {
            UserData userData = new UserData();
            userData.setClType(cltype);
            userData.setCqch(cqch);
            userData.setCreateTime(new Date());
            userData.setOpenId(openId);
            userData.setZhi(new BigDecimal(value));
            System.out.println("userData: " + userData);
            userDataService.insert(userData);
            return "success";
        } catch (Exception e) {
            logger.error("[保存测量结果出错]:openid:" + openId + "cltype:" + type + " value: " + value, e, e.getMessage());
            return "fail";
        }
    }

    @GetMapping("list")
    public String list(String threeSession) {
        // 用户信息校验
        if (StringUtils.isBlank(threeSession)) {
            return "empty threeSession";
        }
        String sessionCode = LocalCache.getInStance().getLocalCache(threeSession);
        if (StringUtils.isBlank(sessionCode)) {
            return "fail";
        }
        String sessionKey = StringUtils.split(sessionCode, "^#^")[0];
        String openId = StringUtils.split(sessionCode, "^#^")[1];

        try {
            UserDataQuery param = new UserDataQuery();
            param.setOpenId(openId);
            param.setClType(TestTypeEnum.Blood_Sugar.getCode());
            List<UserData> blood = userDataService.selectLastThree(param);
            setBlod(blood);
            param.setClType(TestTypeEnum.Uric_Acid.getCode());
            List<UserData> uric = userDataService.selectLastThree(param);
            setData(uric, TestTypeEnum.Uric_Acid);
            param.setClType(TestTypeEnum.Cholesterol.getCode());
            List<UserData> chol = userDataService.selectLastThree(param);
            setData(chol, TestTypeEnum.Cholesterol);
            param.setClType(TestTypeEnum.Triglyceride.getCode());
            List<UserData> trig = userDataService.selectLastThree(param);
            setData(trig, TestTypeEnum.Triglyceride);
            UdVO result = new UdVO(blood, uric, chol, trig);
            return JsonUtils.toJson(result);
        } catch (Exception e) {
            logger.error("[查询测量结果出错]:openid:");
            return "fail";
        }
    }

    private void setBlod(List<UserData> blood) {
        if (CollectionUtil.isNotEmpty(blood)) {
            for (UserData userData : blood) {
                userData.setYear(DateUtil.year(userData.getCreateTime()));
                userData.setMonth(DateUtil.month(userData.getCreateTime()) + 1);
                userData.setDay(DateUtil.dayOfMonth(userData.getCreateTime()));
                userData.setHhmm(DateUtil.format(userData.getCreateTime(), "HH:mm") + "     ");
                userData.setStrcqch(userData.getCqch() == 0 ? "餐前" : "餐后");
                String bd = userData.getZhi() != null ? NumberUtil.roundStr(userData.getZhi().toString(), 1) : "0";
                userData.setZhi(new BigDecimal(bd));
            }
        }
    }

    private void setData(List<UserData> uric, TestTypeEnum type) {
        if (CollectionUtil.isNotEmpty(uric)) {
            for (UserData userData : uric) {
                userData.setYear(DateUtil.year(userData.getCreateTime()));
                userData.setMonth(DateUtil.month(userData.getCreateTime()) + 1);
                userData.setDay(DateUtil.dayOfMonth(userData.getCreateTime()));
                userData.setHhmm(DateUtil.format(userData.getCreateTime(), "HH:mm") + "     ");
                if (type == TestTypeEnum.Uric_Acid) {
                    String bd = userData.getZhi() != null ? NumberUtil.roundStr(userData.getZhi().toString(), 0) : "0";
                    userData.setZhi(new BigDecimal(bd));
                } else if (type == TestTypeEnum.Cholesterol) {
                    String bd = userData.getZhi() != null ? NumberUtil.roundStr(userData.getZhi().toString(), 1) : "0";
                    userData.setZhi(new BigDecimal(bd));
                } else if (type == TestTypeEnum.Triglyceride) {
                    String bd = userData.getZhi() != null ? NumberUtil.roundStr(userData.getZhi().toString(), 2) : "0";
                    userData.setZhi(new BigDecimal(bd));
                }
            }
        }
    }
}
